package com.wk.wechattool.service;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.content.Intent;
import android.graphics.Path;
import android.graphics.PointF;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import com.wk.wechattool.tool.FrindsLikeTool;
import com.wk.wechattool.tool.WeChatSportTool;
import com.wk.wechattool.bean.CmdType;
import com.wk.wechattool.bean.MyEvenBusBean;
import com.wk.wechattool.tool.WkLog;
import com.wk.wechattool.tool.tasktool.HeartBeatTask;
import com.wk.wechattool.tool.tasktool.WkHeartBeatTool;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MyAccessibilityService extends AccessibilityService {
    private WkHeartBeatTool  wkHeartBeatTool = new WkHeartBeatTool() ; ;
    private WeChatSportTool weChatSportTool;
    private FrindsLikeTool frindsLikeTool ;
    private AccessibilityNodeInfo rootNodeInfo ;

    @Override
    protected void onServiceConnected() {
        WkLog.d("辅助功能 onServiceConnected");
        weChatSportTool = new WeChatSportTool( ) ;
        frindsLikeTool = new FrindsLikeTool( ) ;
        EventBus.getDefault().register(this);
    }


    /**
     * 监听窗口变化的回调 。
     */
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        rootNodeInfo = getRootInActiveWindow() ;
    }

    private boolean isDoWxSportLike = false ;
    private boolean isDoWxFrindLike = false ;
    private HeartBeatTask heartMoveUp = new HeartBeatTask( ) {
        @Override
        public void run() {
            moveUp();

            if(rootNodeInfo==null){
                return;
            }

            if(isDoWxSportLike){
                weChatSportTool.starAction(rootNodeInfo   );
            }

            if(isDoWxFrindLike){
                frindsLikeTool.starAction(rootNodeInfo);
            }

        }
    };

    private HeartBeatTask heartMoveDown = new HeartBeatTask( ) {
        @Override
        public void run() {
            moveDown();

            if(rootNodeInfo==null){
                return;
            }

            if(isDoWxSportLike){
                weChatSportTool.starAction(rootNodeInfo   );
            }

            if(isDoWxFrindLike){
                frindsLikeTool.starAction(rootNodeInfo);
            }
        }
    };

    @Override
    public void onInterrupt() {

    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onMessageEvent(MyEvenBusBean event) {
        CmdType  cmdType = event.getCmdType() ;
        WkLog.d("收到指令 cmdType=="+cmdType);
        if(cmdType == CmdType.SCREENSHOT){
            int sysVersion =  Build.VERSION.SDK_INT;
            if(sysVersion>=28){
                performGlobalAction(GLOBAL_ACTION_TAKE_SCREENSHOT) ;
            }else{
                toastMsg("9.0才支持" );
            }
            WkLog.d("sysVersion=="+sysVersion);

        }

        else if(cmdType == CmdType.GLOBAL_BACK){
            performGlobalAction(GLOBAL_ACTION_BACK) ;
        }

        else  if(cmdType == CmdType.CLICK_POINT){
            clickThePoint(event.getPointF() );
        }

        else if(cmdType ==CmdType.MOVE_UP){
            wkHeartBeatTool.shutDownTheBeatAction(heartMoveUp);
            // todo 优化执行的间隔时间 ，滑动时间
            wkHeartBeatTool.startTheBeatAction( heartMoveUp ,300);
        }

        else if(cmdType ==CmdType.MOVE_DOWN){
            wkHeartBeatTool.shutDownTheBeatAction(heartMoveDown);
            wkHeartBeatTool.startTheBeatAction( heartMoveDown ,300);
        }

        else if(cmdType ==CmdType.STOP_ALL){
            isDoWxSportLike =false ;
            isDoWxFrindLike =false ;
            wkHeartBeatTool.shutDownTheBeatAction(heartMoveUp);
            wkHeartBeatTool.shutDownTheBeatAction(heartMoveDown);
        }

        else if(cmdType ==CmdType.WXSPORT){
            isDoWxSportLike =true ;
        }
        else if(cmdType ==CmdType.FRIND_LIKE){
            isDoWxFrindLike =true ;
        }

        else {
            gestureScoroll( cmdType) ;
        }
    }

    private DisplayMetrics displayMetrics ;

    private void moveUp(){
        if(displayMetrics==null){
            displayMetrics = getResources().getDisplayMetrics();
        }
        Path path = new Path();
        int width =displayMetrics.widthPixels;
        int height =displayMetrics.heightPixels;
        // todo 优化滑动需要的时间设置 ，滑屏耗时
        int duration =50 ;
        path.moveTo(width/2f, height/6f*2);
        path.lineTo(width/2f, height/6f  );

        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
        gestureBuilder.addStroke(new GestureDescription.StrokeDescription(path, 0, duration));
        dispatchGesture(gestureBuilder.build(), null, null);
    }

    private void moveDown(){
        if(displayMetrics==null){
            displayMetrics = getResources().getDisplayMetrics();
        }
        Path path = new Path();
        int width =displayMetrics.widthPixels;
        int height =displayMetrics.heightPixels;
        int duration =100 ;
        path.moveTo(width/2f, height/6f);
        path.lineTo(width/2f, height/6f *2);

        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
        gestureBuilder.addStroke(new GestureDescription.StrokeDescription(path, 0, duration));
        dispatchGesture(gestureBuilder.build(), null, null);
    }

    private void gestureScoroll(CmdType moveType){
        if(displayMetrics==null){
            displayMetrics = getResources().getDisplayMetrics();
        }

        Path path = new Path();
        int width =displayMetrics.widthPixels;
        int height =displayMetrics.heightPixels;
        int duration =50 ;

        if(moveType == CmdType.MOVE_LEFT){
            path.moveTo( width/4f*3, height/2f);
            path.lineTo(width/4f, height/2f);
        }

        else if(moveType == CmdType.MOVE_RIGHT){
            path.moveTo( width/4f, height/2f);
            path.lineTo(width/4f*3, height/2f);
        }

        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
        gestureBuilder.addStroke(new GestureDescription.StrokeDescription(path, 0, duration));
        dispatchGesture(gestureBuilder.build(), null, null);
    }

    /**
     *  fixme 部分应用 点击无效 ，例如 美团众包。
     *  原理分析;  AccessibilityService
     */
    private void clickThePoint(PointF point  ){
        GestureDescription.Builder builder = new GestureDescription.Builder();
        Path p = new Path();
        p.moveTo(point.x, point.y);
        builder.addStroke(new GestureDescription.StrokeDescription(p, 0, 50L));
        dispatchGesture( builder.build(), null,null);
    }


    @Override
    public boolean onUnbind(Intent intent) {
        WkLog.d("辅助功能 取消授权");
        EventBus.getDefault().unregister(this);
        return super.onUnbind(intent);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        this. stopSelf();
        WkLog.d("辅助功能 onDestroy");
    }


    private void toastMsg(final String msg){
        Handler handlerThree=new Handler(Looper.getMainLooper());
        handlerThree.post(new Runnable(){
            public void run(){
                Toast.makeText(getApplicationContext() ,msg ,Toast.LENGTH_SHORT).show();
            }
        });
    }
}


/*




 */